<template>
  <div class="cGrid relative z-2 flex flex-wrap">
    <!-- 奖品Item -->
    <div
      class="prizeItem"
      v-for="(item, index) in list"
      :class="{ prizeActive: index === nowPrizeIndex }"
      :key="index"
      @click="itemClick(item)"
    >
      <div>{{ index + 1 }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

interface IItem {}
interface IProps {
  list: IItem[]
}
const nowPrizeItem: Ref<IItem> = ref({})
const nowPrizeIndex = ref(-1)

const props = withDefaults(defineProps<IProps>(), {
  list: () => [],
})
const emits = defineEmits(['itemClick'])
const itemClick = async (item: IItem) => {
  await drawRun({ list: props.list, delay: 50 }, (k: number) => {
    nowPrizeIndex.value = k
  })
  await drawRun({ list: props.list, delay: 100, stopIndex: 6 }, (k: number) => {
    nowPrizeIndex.value = k
  })
  emits('itemClick', item)
}
const drawRun = async (
  option: { list: IItem[]; delay: number; stopIndex?: number },
  cbFn: (k: number) => void
) => {
  const { list, delay, stopIndex } = option
  return new Promise((resolve, _reject) => {
    let max = list.length
    list.every((_v, k) => {
      setTimeout(() => {
        requestAnimationFrame(() => {
          if (cbFn) {
            cbFn(k)
          }
          if (k === max - 1 || k === stopIndex) {
            return resolve(true)
          }
        })
      }, k * delay)
      if (stopIndex === k) {
        return false
      }
      return true
    })
  })
}
// defineExpose({
//   name,
// })
</script>

<style lang="scss">
.cGrid {
  .prizeItem {
    width: 80px;
    height: 80px;
    position: relative;
    margin-bottom: 5px;
    margin-right: 3px;
    background-size: 100%;
    // background-image: url();
    background-color: grey;
    &:nth-child(4n) {
      margin-right: 0;
    }
  }
  .prizeActive {
    position: relative;
    background-size: 100%;
    background-color: #999;
    // background-image: v-bind("'url('+imgObj?.lotteryBoxSelect+')'");
  }
}
</style>
